<template>
  <m-infinite
    v-model="loading"
    :isFinished="isFinished"
    @onLoad="getPexlesListData"
  >
    <m-waterfall
      class="px-1 w-full"
      :data="pexelsList"
      nodeKey="name"
      :column="isMobileTerminal ? 2 : 5"
      :picturePreReading="false"
    >
      <template v-slot="{ item, width }">
        <listItem @click="onToPins" :data="item" :width="width"></listItem>
      </template>
    </m-waterfall>
  </m-infinite>

  <!-- 详情内容展示 -->
  <transition
    :css="false"
    @before-enter="beforeEnter"
    @enter="enter"
    @leave="leave"
  >
    <pinsVue v-if="isVisablePins" :id="currentPins.id"></pinsVue>
  </transition>
</template>

<script setup>
import { isMobileTerminal } from '@/utils/flexible'
import listItem from './item.vue'
import { getPexlesList } from '@/api/pexels'
import { computed, onMounted, ref } from 'vue'
import pinsVue from '../../../pins/components/pins.vue'
import gsap from 'gsap'
import { useEventListener } from '@vueuse/core'

const loading = ref(false)
const isFinished = ref(false)

const pexelsList = ref([])
/*
 *@description: 调取后台数据
 *@author: Mr.Tang
 *@date: 2023-12-16 15:54:52
 *@version: V1.0
 */
const getPexlesListData = async () => {
  //如果数据全部加载完成就不需要再加载了
  if (isFinished.value) {
    return
  }
  if (pexelsList.value.length === 0) {
    pexelsList.value = await getPexlesList()
  } else {
    const result = await getPexlesList()
    pexelsList.value.push(...result)
  }

  if (pexelsList.value.length >= 100) {
    isFinished.value = true
  }
  loading.value = false
}

onMounted(() => {
  getPexlesListData()
})

const isVisablePins = ref(false)

const currentPins = ref({})

const onToPins = (item) => {
  history.pushState(null, null, `/pins/${item.id}`)
  isVisablePins.value = true
  currentPins.value = item
}

const beforeEnter = (el) => {
  gsap.set(el, {
    scaleX: 0,
    scaleY: 0,
    transformOrigin: '0 0',
    translateX: currentPins.value.location?.translateX,
    translateY: currentPins.value.location?.translateY,
    opacity: 0
  })
}

const enter = (el, done) => {
  gsap.to(el, {
    duration: 0.5,
    scaleX: 1,
    scaleY: 1,
    translateX: 0,
    translateY: 0,
    opacity: 1,
    onComplete: done
  })
}

const leave = (el, done) => {
  gsap.to(el, {
    duration: 0.5,
    scaleX: 0,
    scaleY: 0,
    translateX: currentPins.value.location?.translateX,
    translateY: currentPins.value.location?.translateY,
    opacity: 0,
    onComplete: done
  })
}

useEventListener(window, 'popstate', () => {
  isVisablePins.value = false
})
</script>

<style lang="scss" scoped></style>
